package cn.nc.controller;


import cn.nc.entity.User;
import cn.nc.repository.ArticleRepository;
import cn.nc.repository.UserRepository;
import cn.nc.service.ArticleService;
import cn.nc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;



@Controller
public class LoginController {

    @Autowired
    ArticleService articleService;

    @Autowired
    UserService userService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    ArticleRepository articleRepository;


    @RequestMapping("/login")
    public String login(){
        return "user/login";
    }


    @GetMapping("/logout")
    public String logout(){
        return "user/logout";
    }


    @GetMapping("/register")
    public String register(){
        return "user/register";
    }

    @PostMapping("/register")
    public String registerUser(String email, String username, String password, Model model){
        if(userService.register(email,username,password)){
            return "redirect:/login";
        }else{
            model.addAttribute("msg","用户已注册!");
            return "user/register";
        }
    }


    @GetMapping("/user")
    public String user(Model model){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User)authentication.getPrincipal();

        return userInfo(user.getId(),model);
    }


    @GetMapping("/user/{id}")
    public String userInfo(@PathVariable("id")Integer id, Model model) {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        User user = userService.findByUserId(((User) authentication.getPrincipal()).getId());
//        User user = userRepository.findById(1).get();
//        User user = userRepository.findById(((User)authentication.getPrincipal()).getId()).get();
//        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//        ObjectMapper mapper = new ObjectMapper();
//        Map userMap = new HashMap(10);
//        userMap.put("User",user);
//        System.out.println(user);
//        System.out.println(mapper.writeValueAsString(userMap));

//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = userRepository.findById(id).get();

        model.addAttribute("user",user);
        model.addAttribute("msg","aaa");

        return "/user";


    }

}
